
//
//  YYYNewFeatureView.swift
//  HotNews
//
//  Created by YYY on 2017/10/17.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit
// MARK: 新特性界面
class YYYNewFeatureView: UIView {
    
    //滑动视图
    private lazy var mainScrollView = UIScrollView(frame: kMainScreenBounds, isBounces: false)
    //进入按钮
    private lazy var enterButton = UIButton(title: "进入微博", fontSize: 16, normalColor: UIColor.white, target: self, action: #selector(enterAction), backgroundImageName: "new_feature_finish_button")
    //分页控件
    private lazy var pageControl = UIPageControl(number: 4)
    
    //构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        //初始化控件
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 进入微博
    @objc private func enterAction()
    {
        //移除视图
        removeFromSuperview()
    }
}

extension YYYNewFeatureView
{
    //初始化控件
    private func setupUI()
    {
        //添加子视图
        addSubview(mainScrollView)
        addSubview(enterButton)
        addSubview(pageControl)
        
        //进入按钮
        //隐藏进入按钮
        enterButton.isHidden = true
        enterButton.setY(newY: kDeviceHeight-200)
        enterButton.center.x = center.x
        enterButton.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), for: .highlighted)
        
        //分页
        pageControl.frame = CGRect(x: 0, y: enterButton.bottom+10, width: kDeviceWidth, height: 30)
        
        //添加四个图片视图
        let count = 4
        for i in 0..<count
        {
            let imageName = "new_feature_\(i+1)"
            let imageView = UIImageView(image: UIImage(named: imageName))
            imageView.frame = kMainScreenBounds.offsetBy(dx: CGFloat(i) * kDeviceWidth, dy: 0)
            mainScrollView.addSubview(imageView)
        }
      
        //设置contentSize大小
        mainScrollView.contentSize = CGSize(width: CGFloat(count+1) * kDeviceWidth, height: kDeviceHeight)
        //设置代理
        mainScrollView.delegate = self
    }
}

extension YYYNewFeatureView: UIScrollViewDelegate
{
    //减速结束
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x / scrollView.width)
        print("滑动到第\(page)页")
        if page == mainScrollView.subviews.count {
            //最后一页移除视图
            removeFromSuperview()
        }
        //最后第二页显示进入按钮
        enterButton.isHidden = page != (mainScrollView.subviews.count - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //一滑动就隐藏进入按钮
        enterButton.isHidden = true
        //滑动过程中的偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.width + 0.5)
        pageControl.currentPage = page
        //最后一页，隐藏分页控件
        pageControl.isHidden = (page == mainScrollView.subviews.count)
    }
}

